package services

import (
	"fmt"
	"github.com/goravel/framework/facades"
	"github.com/mojocn/base64Captcha"
	"image/color"
)

type CaptchaService struct {
	Store  base64Captcha.Store
	Driver base64Captcha.Driver
}

func NewCaptchaService() *CaptchaService {
	return &CaptchaService{
		Store: base64Captcha.DefaultMemStore,
	}
}

func (s *CaptchaService) Generate() (id, b64s, answer string, err error) {
	captchaType := facades.Config().GetString("app.captcha.type")
	var captcha *base64Captcha.Captcha
	fmt.Println(captchaType)
	switch captchaType {
	case "audio":
		driver := base64Captcha.DriverAudio{
			Length: 6,
		}
		captcha = base64Captcha.NewCaptcha(&driver, s.Store)
	case "string":
		driver := base64Captcha.DriverString{
			Height: facades.Config().GetInt("app.captcha.height"),
			Width:  facades.Config().GetInt("app.captcha.width"),
			Length: facades.Config().GetInt("app.captcha.length"),
		}
		driver.ConvertFonts()
		captcha = base64Captcha.NewCaptcha(&driver, s.Store)
	case "math":
		driver := base64Captcha.DriverMath{
			Height:  facades.Config().GetInt("app.captcha.height"),
			Width:   facades.Config().GetInt("app.captcha.width"),
			BgColor: &color.RGBA{0, 0, 0, 20},
		}
		driver.ConvertFonts()
		captcha = base64Captcha.NewCaptcha(&driver, s.Store)
	case "chinese":
		driver := base64Captcha.DriverChinese{
			Height: facades.Config().GetInt("app.captcha.height"),
			Width:  facades.Config().GetInt("app.captcha.width"),
			Length: 5,
			Source: "中文字库这是测试广州欢网科技",
		}
		driver.ConvertFonts()
		captcha = base64Captcha.NewCaptcha(&driver, s.Store)
	default:
		driver := base64Captcha.DriverDigit{
			Height:   facades.Config().GetInt("app.captcha.height"),
			Width:    facades.Config().GetInt("app.captcha.width"),
			MaxSkew:  0.7,
			DotCount: 20,
			Length:   5,
		}
		captcha = base64Captcha.NewCaptcha(&driver, s.Store)
	}
	id, b64s, answer, err = captcha.Generate()
	return
}

func (s *CaptchaService) Verify(id, answer string, clear bool) bool {
	return s.Store.Verify(id, answer, clear)
}
